package com.runtu.domain.activity.service.trial.node;


import com.alibaba.fastjson.JSON;
import com.runtu.domain.activity.model.entity.MarketProductEntity;
import com.runtu.domain.activity.model.entity.TrialBalanceEntity;
import com.runtu.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import com.runtu.domain.activity.model.valobj.SkuVO;
import com.runtu.domain.activity.service.discount.IDiscountCalculateService;
import com.runtu.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import com.runtu.domain.activity.service.trial.Thread.QueryGroupBuyActivityDiscountVOThreadTask;
import com.runtu.domain.activity.service.trial.Thread.QuerySkuVOFromDBThreadTask;
import com.runtu.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import com.runtu.types.design.framework.tree.StrategyHandler;
import com.runtu.types.enums.ResponseCode;
import com.runtu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 营销优惠节点
 * @create 2024-12-14 14:30
 */
@Slf4j
@Service
public class MarketNode extends AbstractGroupBuyMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private EndNode endNode;
    @Resource
    private  ErrorNode errorNode;
    @Resource
    private  TagNode tagNode;

    //只要是IDiscountCalculateService接口下的实现 全部都注入了 Key就是这些实现类上Service注解内的 ZJ，N等
    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;


    //异步数据的加载
    @Override
    protected void multiThread(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext)
            throws ExecutionException, InterruptedException, TimeoutException {
        //异步查询活动配置
        QueryGroupBuyActivityDiscountVOThreadTask  queryGroupBuyActivityDiscountVOThreadTask =
                new QueryGroupBuyActivityDiscountVOThreadTask(requestParameter.getSource(),requestParameter.getChannel(),requestParameter.getGoodsId(),repository);
        /*田间futuretask 也就是未来操作*/
        FutureTask<GroupBuyActivityDiscountVO> groupBuyActivityDiscountVOFutureTask = new FutureTask<>(queryGroupBuyActivityDiscountVOThreadTask);
        /*丢到线程池里面 丢进去就开始执行 并不等get才执行*/
        threadPoolExecutor.execute(groupBuyActivityDiscountVOFutureTask);

        // 异步查询商品信息 - 在实际生产中，商品有同步库或者调用接口查询。这里暂时使用DB方式查询。
        QuerySkuVOFromDBThreadTask querySkuVOFromDBThreadTask = new QuerySkuVOFromDBThreadTask(requestParameter.getGoodsId(), repository);
        FutureTask<SkuVO> skuVOFutureTask = new FutureTask<>(querySkuVOFromDBThreadTask);
        threadPoolExecutor.execute(skuVOFutureTask);

        /*把这两步数据写道上下文DynamicContext中 对于一些复杂场景，获取数据的操作，有时候会在下N个节点获取，这样前置查询数据，可以提高接口响应效率*/
        dynamicContext.setGroupBuyActivityDiscountVO(groupBuyActivityDiscountVOFutureTask.get(timeout, TimeUnit.MINUTES));
        dynamicContext.setSkuVO(skuVOFutureTask.get(timeout,TimeUnit.MINUTES));


        log.info("拼团商品查询试算服务-MarketNode userId:{} 异步线程加载数据「GroupBuyActivityDiscountVO、SkuVO」完成", requestParameter.getUserId());

    }

    @Override
    public TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {

        log.info("拼团商品查询试算服务-MarketNode userId:{} requestParameter:{}", requestParameter.getUserId(), JSON.toJSONString(requestParameter));

        // 拼团优惠试算逻辑
        /*1、先把上下文的数据拿出来*/// 获取上下文数据
        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        if (groupBuyActivityDiscountVO == null) {
            return router(requestParameter, dynamicContext);
        }
        GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = groupBuyActivityDiscountVO.getGroupBuyDiscount();
        if (groupBuyDiscount == null) return router(requestParameter, dynamicContext);
        /*2、获取SKu的信息*/
        SkuVO skuVO = dynamicContext.getSkuVO();
        if (null == skuVO) return router(requestParameter, dynamicContext);
        /*3、获取打折的类型  优惠试算*/
        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyDiscount.getMarketPlan());
        if (discountCalculateService == null) {
            throw new AppException(ResponseCode.E0001.getCode(),ResponseCode.E0001.getInfo());
        }
        /*4、再计算折扣价格*/
        BigDecimal payPrice = discountCalculateService.calculate(requestParameter.getUserId(), skuVO.getOriginalPrice(), groupBuyDiscount);
        /*5、价格写道上下文dynamicContext中*/
        dynamicContext.setDedutionPrice(skuVO.getOriginalPrice().subtract(payPrice));
        dynamicContext.setPayPrice(payPrice);



        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        // 不存在配置的拼团活动，走异常节点
        if (dynamicContext.getGroupBuyActivityDiscountVO() == null ||
                dynamicContext.getSkuVO() == null ||
                dynamicContext.getDedutionPrice() == null) {
            return  errorNode;
        }

        return tagNode;
    }
}
